package cn.sharp.bbs.common;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class CommonConfig {

    private static ApplicationContext applicationContext;
    private static Environment env;

    @Autowired
    public void setApplicationContext(ApplicationContext applicationContext) {
        CommonConfig.applicationContext = applicationContext;
        CommonConfig.env = CommonConfig.applicationContext.getEnvironment();
    }


    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    public static Environment getEnv() {
        return env;
    }

    @Bean
    public WebMvcConfigurer webMvcConfigurer() {

        return new WebMvcConfigurer() {
            /**
             * 跨域配置
             * @param registry: 跨域策略注册项
             */
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**")
                        .allowedOrigins("*")
                        .allowedMethods(RequestMethod.GET.name(),
                                RequestMethod.POST.name(),
                                RequestMethod.PUT.name(),
                                RequestMethod.DELETE.name());
            }

            /**
             * 拦截器配置
             * @param registry: 拦截器注册项
             */
            @Override
            public void addInterceptors(InterceptorRegistry registry) {
                registry.addInterceptor(new PermissionInterceptor())
                        .excludePathPatterns("assets/**");
            }

            /**
             * 资源访问控制
             * @param registry: 资源处理器注册项
             */
            @Override
            public void addResourceHandlers(ResourceHandlerRegistry registry){
                registry.addResourceHandler("/assets/**")
                        .addResourceLocations("file:assets/");
            }
        };
    }
}
